package security;

import java.awt.event.*;
import javax.swing.*;

import java.awt.*;
import java.sql.*;

public class NewAccount extends JFrame {

	private static final long serialVersionUID = 1L;
	private static JLabel userName;
	private static JLabel passWord;
	private static JButton submit;
	private static JTextField newUsername;
	JPasswordField newPassword;
	private static Statement stmnt = null;
	private static Connection connect;
	@SuppressWarnings("unused")
	private static String username, password;

	private static void createConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			// Get a connection
			connect = DriverManager.getConnection(JavaDB.dbUrl, "root", "root");
		} catch (Exception except) {
			except.printStackTrace();
		}
	}

	public static void main(String args[]) {
		NewAccount window = new NewAccount();
		window.setVisible(false);
		window.addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}

	public NewAccount() {
		super("New Account");

	}

	public void frame() {
		Container c = getContentPane();
		c.setLayout(new FlowLayout());
		userName = new JLabel("Username:");
		c.add(userName);
		newUsername = new JTextField(20);
		c.add(newUsername);
		passWord = new JLabel("\nPassword:");
		c.add(passWord);
		newPassword = new JPasswordField(20);
		c.add(newPassword);
		submit = new JButton("Submit");
		c.add(submit);
		submit.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				if (e.getSource().equals(submit)) {
					try {
						insert();
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			}
		});
		;

		this.setLocationRelativeTo(getRootPane());
		setSize(325, 150);
		setVisible(true);
	}

	@SuppressWarnings("deprecation")
	public void insert() throws SQLException {
		try {
			createConnection();
			stmnt = connect.createStatement();
			stmnt.execute("Insert into userTable values('"
					+ newUsername.getText() + "','" + newPassword.getText()
					+ "')");
			JOptionPane.showMessageDialog(this, "Thank you.");
			this.setVisible(false);
			JavaDB.firstTime();
		} catch (SQLException ex) {

			stmnt = connect.createStatement();
			stmnt.execute("Create Table userTable"
					+ "(Username varchar(25),Password varchar(25))");
			insert();

		}
	}

	public void action() {
		frame();
		NewAccount window = new NewAccount();
		window.addWindowListener(new WindowAdapter() {

			public void windowClosing(WindowEvent e) {
				System.exit(0);
			}
		});
	}
}